﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Imageo.bintje;
using log4net;
using System.Security.Policy;

namespace Imageo.ui
{
    public partial class UserProfile : System.Web.UI.Page
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        protected void Page_Load(object sender, EventArgs e)
        {
            bintje.imageoSession currentSession = Session["BintjeSession"] as imageoSession;

            if (currentSession == null) Response.Redirect("~/UI/ErrorLoginFirst.aspx");

            if (!Page.IsPostBack)
            {
                msgStatus.Text = "";

                ServiceAPI service = new ServiceAPI();
                userRequest ureq = new userRequest();
                ureq.session = currentSession;
                ureq.userId = currentSession.userId;
                if (log.IsErrorEnabled) log.Debug("Calling: service.getUserDetails(ureq)");
                userResponse uresp = ServiceHelper.HandleBintjeErrors(this, service.getUserDetails(ureq));

                txtLogin.Text = uresp.user.login;
                txtNickname.Text = uresp.user.nickName;

                lblProUser.Visible = uresp.user.professional;
                lnkRequestPro.Visible = !uresp.user.professional;

                txtBackColor.Text = uresp.user.background;
                txtForeColor.Text = uresp.user.foreground;
                txtImageUrl.Text = uresp.user.url;
                chkBorders.Checked = uresp.user.borders;


                if (uresp.user.preferences != null)
                {
                    chkReceiveEmails.Checked = uresp.user.preferences.receiveEmails;
                }

                if (uresp.user.imageUrl != null)
                {
                    imgUserPicture.ImageUrl = uresp.user.imageUrl;
                }
            }

            rowPro1.Visible = lblProUser.Visible;
            rowPro2.Visible = lblProUser.Visible;
            rowPro3.Visible = lblProUser.Visible;
            rowPro4.Visible = lblProUser.Visible;
            rowPro5.Visible = lblProUser.Visible;
            string proUrl = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port.ToString() + this.ResolveUrl("~/pro/" + currentSession.userId.ToString());
            txtUrl.Text = proUrl;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                bintje.imageoSession currentSession = Session["BintjeSession"] as imageoSession;
                if (currentSession == null) Response.Redirect("~/UI/ErrorLoginFirst.aspx");

                msgStatus.Text = "The changes have been stored successfully";

                ServiceAPI service = new ServiceAPI();
                userRequest ureq = new userRequest();
                ureq.session = currentSession;
                ureq.userId = currentSession.userId;
                if (log.IsErrorEnabled) log.Debug("Calling: service.getUserDetails(ureq)");
                userResponse uresp = ServiceHelper.HandleBintjeErrors(this, service.getUserDetails(ureq));

                editUserRequest eureq=new editUserRequest();
                eureq.session=currentSession;
                eureq.user=uresp.user;                

                eureq.user.login = txtLogin.Text;
                eureq.user.nickName = txtNickname.Text;
                eureq.user.professional = lblProUser.Visible;
                eureq.user.preferences = new userPreferences();
                eureq.user.preferences.receiveEmails = chkReceiveEmails.Checked;
                eureq.user.background = txtBackColor.Text;
                eureq.user.foreground = txtForeColor.Text;
                eureq.user.borders = chkBorders.Checked;
                eureq.user.url = txtImageUrl.Text;
               
                if (fupPicture.HasFile)
                {
                    // Save the file to a temporary location
                    string baseLocation = Server.MapPath("~/Upload/");
                    string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(fupPicture.PostedFile.FileName);
                    fupPicture.PostedFile.SaveAs(baseLocation + fileName);

                    try {

                    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(baseLocation + fileName);
                    System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();

                    byte[] rawData=(byte[])converter.ConvertTo(bmp, typeof(byte[]));

                    eureq.user.image=new image();
                    eureq.user.image.fileName=fileName;
                    eureq.user.image.height=bmp.Height;
                    eureq.user.image.width=bmp.Width;
                    eureq.user.image.imagedata=rawData;
                    }
                    catch(Exception exc)
                    {
                        msgStatus.Text = "There was an error updating the user profile";
                    }
                } 
                else 
                {
                    // keep the old one?
                }

                if (log.IsErrorEnabled) log.Debug("Calling: service.editUser(eureq)");
                uresp = ServiceHelper.HandleBintjeErrors(this, service.editUser(eureq));

                // Get the url back and show that
                if (uresp.user.imageUrl != null)
                {
                    imgUserPicture.ImageUrl = uresp.user.imageUrl;
                }

            }
            catch (Exception exc)
            {
                msgStatus.Text = "There was an error storing the changes";
            }
        }
    }
}
